/*
 * Javascript Benchmark tool
 * By Olivier St-Laurent
 * 
 */

if (typeof window.performance === 'undefined') {
    window.performance = {};
    performance.now = (function() {
      return performance.now       ||
             performance.mozNow    ||
             performance.msNow     ||
             performance.oNow      ||
             performance.webkitNow ||
             function() { return new Date().getTime(); };
    })();
}

var X_JSBenchStart = window.performance.now();
var JSBenchStart = function() {
    X_JSBenchStart = window.performance.now();
};
var JSBenchGet = function() {
    return window.performance.now() - X_JSBenchStart;
};
var JSBenchClog = function(minimum) {
    var time = JSBenchGet();
    if (+time >= (minimum || 0)) console.log(time.toFixed(2) + ' ms');
};
var JSBenchFunc = function(functionToTest, repeat, nbAvg) {
    var start = window.performance.now();
    this.reset = function() {
        var end = this.end();
        start = window.performance.now();
        return end;
    };
    this.end = function() {
        return window.performance.now() - start;
    };
    this.clog = function() {
        console.log(this.end());
    };
    if (functionToTest !== undefined) {
        if (repeat === undefined) repeat = 100000;
        if (nbAvg === undefined) nbAvg = 10;
        var total = 0;
        var nbTimes;
        start = window.performance.now();
        for (nbTimes = 0; nbTimes < nbAvg; nbTimes++) {
            for (var i = 0; i < repeat; i++) {
                functionToTest();
            }
            total += this.reset();
        }
        console.log(Math.round(total / nbTimes) + ' ms (average over '+nbAvg+' times '+repeat+' executions)');
    }
};
